/**
 * @author: lichuang.
 * @date: 2019/11/06
 * @description:公共方法
 */

import Encrypt from '../public/encrypt'

let Utils = Utils || {}

//生产环境
// Utils.apiUrl = ''
//Utils.imgUrl = ''
// http://member.frp.mvker.com/
//开发测试环境

// Utils.apiUrl = 'http://testapi.houaijk.com';
// Utils.apiUrl = 'http://member.frp.mvker.com/'
// Utils.apiUrl = 'http://dg.frp.mvker.com/';
// Utils.apiUrl = 'http://houai-api.frp.mvker.com/';
// Utils.apiUrl = 'http://patient.vipgz1.91tunnel.com/AppApi';

// Utils.apiUrl = 'http://houaijk.free.idcfengye.com/AppApi';
// Utils.apiUrl = 'http://58.48.0.90:8181/newapp';
Utils.apiUrl = 'http://api.houaijk.com/newapp';
Utils.imgUrl = 'http://api.houaijk.com/newapp';
// Utils.imgUrl = 'http://58.48.0.90:8181/newapp';

Utils.hlwyy_ghId = 'gh_f82f0ce7b836';	//互联网医院用户小程序
Utils.mbxt_ghld = 'gh_3b39c6f1c15f';		//慢病管理业务小程序

//手机号校验
Utils.isPhone = (value) => {
  let patten = /^1[3|4|5|7|8|9]\d{9}$/.test(value)
  return patten
}

//登录状态
Utils.isLogin = (value) => {
	if (uni.getStorageSync('token') == '' || uni.getStorageSync('token') == null) {
		setTimeout(() => {
			uni.reLaunch({
				url: '/loginabout/login/login',
				success: () =>{
					plus.navigator.closeSplashscreen()
				}
			})
		})
	}else if (!(uni.getStorageSync('token') == '' || uni.getStorageSync('token') == null) && !uni.getStorageSync('userMsg').idcard) {
		setTimeout(() => {
			uni.reLaunch({
				url: '/loginabout/authentication/before',
				success: () =>{
					plus.navigator.closeSplashscreen()
				}
			})
		})
	}else{
		uni.reLaunch({
			url: '/pages/home/home',
			success: () =>{
				plus.navigator.closeSplashscreen()
			}
		})
	}
}

//身份证脱敏
Utils.replaceIdCard = (val) => {
  if (val && val.length == 15) {
    return val.replace(val.slice(4, 11), '*******')
  } else if (val && val.length == 18) {
    return val.replace(val.slice(4, 14), '**********')
  } else if (val && (val.length != 15 || val.length != 18)) {
    return val.replace(val.slice(1, val.length - 1), '*')
  }
}
// 根据身份证号获取年龄
Utils.GetAge = (identityCard) => {
  let len = (identityCard + "").length;
  if (len == 0) {
      return 0;
  } else {
      if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法
      {
          return 0;
      }
  }
  let strBirthday = "";
  if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
  {
      strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
  }
  if (len == 15) {
      strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
  }
  //时间字符串里，必须是“/”
  let birthDate = new Date(strBirthday);
  let nowDateTime = new Date();
  let age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
      age--;
  }
  return age;
}

//手机号脱敏
Utils.replaceNumber = (val) => {
  if (val) {
    return val.replace(val.slice(2, 9), '******')
  } else {
    return ''
  }
}

/**
 * 防抖
 *
 * @param { Function } fn 要执行的方法
 * @param { Number } wait  防抖多少毫秒
 *
 * 在 vue 中使用（注意：不能使用箭头函数，否则this指向不对，并且不能再次封装如：
 * move(){  // 错误调用方式
 *   debounce(function () {
 *   console.log(this.title);
 * }, 1000)}）;
 * 应该直接使用：// 正确调用方式
 * move: debounce(function () {
 *   console.log(this.title);
 * }, 1000)
 */
Utils.debounce = (fn, wait) => {
	let timer = false;
	return function() {
		if(timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(fn, arguments); // 把参数传进去
		}, wait);
	};
}
// 节流
Utils.throttle = function(fn, wait){
	var _self = fn, // 保存需要被延迟执行的函数引用
		timer, // 定时器
		firstTime = true; // 是否是第一次调用
	return function(){
		var args = arguments,
		_me = this;
		if(firstTime){
			_self.apply(_me,args)
			return firstTime = false;
		}
		if(timer) return false
		timer = setTimeout(function(){
			clearTimeout(timer)
			timer = null
			_self.apply(_me,args)
		},wait||500)
	}
	// let timer = null
	// wait = wait || 1000
	// return function(...args) {
	// 	if(timer) return;
	// 	const _this = this
	// 	timer = setTimeout(()=>{
	// 		timer = null
	// 	}, wait)
	// 	fn.apply(fn, args); // 把参数传进去
	// };
}

// 百度坐标系转换为gcj02 微信小程序api可用坐标
Utils.bd09togcj02 = (bd_lon, bd_lat) => {
  let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  let x = bd_lon - 0.0065;
  let y = bd_lat - 0.006;
  let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  let gg_lng = z * Math.cos(theta);
  let gg_lat = z * Math.sin(theta);
  return [gg_lng, gg_lat]
}

// gcj02坐标系转换为百度
Utils.gcj02tobd09 = (lng, lat) => {
  let x_PI = 3.14159265358979324 * 3000.0 / 180.0;
  let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
  let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
  let bd_lng = z * Math.cos(theta) + 0.0065;
  let bd_lat = z * Math.sin(theta) + 0.006;
  return [bd_lng, bd_lat]
}


// 导航
Utils.openMap = (lon, lat) => {
  let lonlat = Utils.bd09togcj02(lon, lat)
  uni.openLocation({
    latitude: lonlat[1],
    longitude: lonlat[0],
    success() {
      console.log('success');
    },
    fail(err) {
      console.log(err)
    }
  });
}


//轻提示
Utils.toast = (val = '') => {
  uni.showToast({
    title: val,
    icon: 'none',
    mask: true,
    duration: 1500
  })
}


//检查本地版本
Utils.checkApp = () => {
   return plus.runtime.versionCode
}


//对象转url参数格式
Utils.queryParams = (data, isPrefix = false) => {
  let prefix = isPrefix ? '?' : ''
  let _result = []
  for (let key in data) {
    let value = data[key]
    if (['', undefined, null].includes(value)) {
      continue
    }
    if (value.constructor === Array) {
      value.forEach(_value => {
        _result.push(key + '[]=' + _value)
      })
    } else {
      _result.push(key + '=' + value)
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}


// 手机定位权限开启/未开启
Utils.openPosition = () => {
	let system = uni.getSystemInfoSync();
	if(system.platform === 'android'){
		var context = plus.android.importClass("android.content.Context")
		var locationManager = plus.android.importClass("android.location.LocationManager")
		var main = plus.android.runtimeMainActivity()
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
		console.log('GPS',mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER))
		if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
			uni.showModal({
				title:'提示',
				content:'请打开定位服务功能',
				showCancel:false,
				success() {
					if(!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)){
						let main = plus.android.runtimeMainActivity();
						let Intent = plus.android.importClass("android.content.Intent");
						let mIntent = new Intent('android.settings.ACTION_SETTINGS');
						main.startActivity(mIntent);//打开系统设置GPS服务页面 
					}else{
						uni.showToast({
							title:'定位功能已启动',
							duration:2000
						})
					}
				}
			})
		}
	}
}

// 设置tabbar
Utils.reviseTabbarByUserType = (type) =>{
	if(type == 0){
		uni.setTabBarItem({
			index: 5,
			visible: false,
		})
		uni.setTabBarItem({
			index: 6,
			visible: false,
		})
		uni.setTabBarItem({
			index: 7,
			visible: false,
		})
	}else if(type == 1){
		uni.setTabBarItem({
			index: 0,
			visible: false,
		})
		uni.setTabBarItem({
			index: 1,
			visible: false,
		})
		uni.setTabBarItem({
			index: 2,
			visible: false,
		})
		uni.setTabBarItem({
			index: 3,
			visible: false,
		})
		uni.setTabBarItem({
			index: 4,
			visible: false,
		})
	}
}

export default Utils
